import Vue from 'vue'
import Vuex from 'vuex'
import { Stomp } from '../websocket/stomp.js'
import UniWebSocket from '../websocket/uniWebSocket.js'
Vue.use(Vuex)
const store = new Vuex.Store({
    state: {
		client:null,
		token:null || sessionStorage.getItem("token"),
		user:null || JSON.parse(sessionStorage.getItem("user")),
		publicMsg:null || JSON.parse(sessionStorage.getItem("publicMsg")), 
		taskMsg:null || JSON.parse(sessionStorage.getItem("taskMsg")),
		isReadTaskList:null || JSON.parse(sessionStorage.getItem("isReadTaskList")),
		myTaskList:null || JSON.parse(sessionStorage.getItem("myTaskList")),
		myCourse:null || JSON.parse(sessionStorage.getItem("myCourse")),
		
	},
    mutations: {
		startSocket(state,val){
			//部署时候需要开8216端口
			//let uri = `ws://47.108.140.232:8216/mobileSocket?userId=${val}`
			let uri = `ws://127.0.0.1:8216/mobileSocket?userId=${val}`
			let ws = new UniWebSocket(uri)
			state.client = new Stomp.over(ws)
			state.client.debug = true
			state.client.connect({"token":val},data=>{
				state.client.subscribe("/user/topic/userMsg",(data)=>{
				state.publicMsg = JSON.parse(data.body)
				sessionStorage.setItem("publicMsg",data.body)
				})
				 state.client.subscribe("/user/task/userTask",(data)=>{
				 state.taskMsg = JSON.parse(data.body)
				 sessionStorage.setItem("taskMsg",  data.body)
				 })
			})
		},
		sendusermsg(state,val){
		   state.stompclient.send("/mysocket/userMsg",{},val)
		},
		disconnect(state,val){
			console.log("ok,come on")
			// 断开连接
			if (state.client) {
				state.client.disconnect()
			}
		},
		setToken(state,val){
			state.token = val
			sessionStorage.setItem("token",val)
		},
		setUser(state,val){
			state.user = val
			let userStr = JSON.stringify(val)
			sessionStorage.setItem("user",userStr)
		},
		loginOut(state){
			state.token = null
			sessionStorage.removeItem("token")
		},
		updateTaskMsg(state,val){
			state.taskMsg = state.taskMsg.filter(f=>f.taskId != val)
			let str = JSON.stringify(state.taskMsg)
			sessionStorage.setItem("taskMsg",str)
		},
		isReadTaskList(state,val){
			state.isReadTaskList = val
			let array = JSON.stringify(val)
			sessionStorage.setItem("isReadTaskList",array)
		},
		myTaskList(state,info){
			state.myTaskList = info
			let array = JSON.stringify(info)
			sessionStorage.setItem("myTaskList",array)
		},
		updateMyTaskList(state,info){
			state.myTaskList = info
			let array = JSON.stringify(info)
			sessionStorage.setItem("myTaskList",array)
		},
		myCourse(state,info){
			state.myCourse = info
			let array = JSON.stringify(info)
			sessionStorage.setItem("myCourse",array)
		},
		
	},
    actions: {
		
	}
})
export default store